package com.cjzuji.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjzuji.rental.Bean.AiDouRequest;
import com.cjzuji.rental.Config.AZJConfig;
import com.cjzuji.rental.Config.AiDouConfig;
import com.cjzuji.rental.dao.*;
import com.cjzuji.rental.mapper.OrderBillMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.pojo.OrderBill;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.service.AiDouService;
import com.cjzuji.rental.util.Tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class AiDouServiceImpl implements AiDouService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    AiDSaveServiceImpl aiDSaveService;
    @Autowired
    AiDouConfig aiDouConfig;
    @Autowired
    OrderBillMapper orderBillMapper;
    @Autowired
    AiDouBillDao aiDouBillDao;

    private static final Logger logger = LoggerFactory.getLogger(AiDouServiceImpl.class);
    @Override
    @Transactional
    public List<Map<String, Object>> getAiDList(String accesstoken){
        String url = aiDouConfig.getGetListUrl();
        AiDouRequest aiDouRequest = new AiDouRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        aiDouRequest.setPageNumber(1);
        aiDouRequest.setPageSize(50);
        aiDouRequest.setRentMode(1);
        int pageNum = 1;  // 从第一页开始
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                aiDouRequest.setPageNumber(pageNum);
                String json = objectMapper.writeValueAsString(aiDouRequest);
                String resStr = Tool.request(url,accesstoken, "", json,"","");
                //logger.info("获取请求结果 {}",resStr);
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                //logger.info("res {}",res);
                // 获取 data → list
                Map<String, Object> dataMap = (Map<String, Object>) res.get("result");
                //logger.info("dataMap {}",dataMap);
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("records");
                //logger.info("list {}",list);
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                        //System.out.println("item~~~~~~~~~~~"+item.toString());
                        String orderId = item.get("sn").toString();
                        //查询订单详情
                        Map<String,Object> orderDetail = getOrderDetailes(accesstoken, orderId);
                        if (orderDetail == null || orderDetail.isEmpty()){
                            logger.info("订单详情为空，跳过 {}",orderDetail);
                            continue;
                        }
                        //logger.info("orderDetail {}",orderDetail);
                        //账单
                        Map<String,Object> orderBill = getBillList(accesstoken,orderId,pageNum);
                        //logger.info("orderBill {}",orderBill);
                        List<Map<String, Object>> orderBillList = (List<Map<String, Object>>) orderBill.get("records");
                        //logger.info("orderBillList {}",orderBillList);
                        aiDSaveService.getListSave(orderId, item,orderDetail,orderBillList);
                    }
                }
                else {
                    break;
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;
    }

    //租用中
    @Override
    @Transactional
    public List<Map<String, Object>> upDateBillList(String accesstoken){
        String url = aiDouConfig.getGetListUrl();
        AiDouRequest aiDouRequest = new AiDouRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        aiDouRequest.setOrderStatus("TO_BE_RETURNED");
        aiDouRequest.setPageNumber(1);
        aiDouRequest.setPageSize(50);
        aiDouRequest.setRentMode(1);
        int pageNum = 1;  // 从第一页开始
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                aiDouRequest.setPageNumber(pageNum);
                String json = objectMapper.writeValueAsString(aiDouRequest);
                String resStr = Tool.request(url,accesstoken, "", json,"","");
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                Map<String, Object> dataMap = (Map<String, Object>) res.get("result");
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("records");
                //logger.info("list {}",list);
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                        //System.out.println("item~~~~~~~~~~~"+item.toString());
                        String orderId = item.get("sn").toString();
                        //查询订单详情
                        Map<String,Object> orderDetail = getOrderDetailes(accesstoken, orderId);
                        //账单
                        Map<String,Object> orderBill = getBillList(accesstoken,orderId,pageNum);
                        //logger.info("orderBill {}",orderBill);
                        List<Map<String, Object>> orderBillList = (List<Map<String, Object>>) orderBill.get("records");
                        logger.info("orderBillList {}",orderBillList);
                        aiDSaveService.getzySave(orderId,item,orderDetail,orderBillList);
                    }
                }
                else {
                    break;
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;
    }

    //查询订单详情
    public Map<String,Object> getOrderDetailes(String accesstoken, String orderSN) throws JsonProcessingException {
        System.out.println("orderSN~~~~~"+orderSN);
        try {
            AiDouRequest aiDouRequest = new AiDouRequest();
            aiDouRequest.setOrderSN(orderSN);
            ObjectMapper objectMapper = new ObjectMapper();
            String JSON=objectMapper.writeValueAsString(aiDouRequest);
            //查询订单详情（rentRecordNo动态传递）
            String detail =aiDouConfig.getGetDetailUrl()+orderSN;
            //post
            String detailStr =  Tool.request(detail,accesstoken,"",JSON,"","");

            ObjectMapper resDetailMapper = new ObjectMapper();
            Map<String,Object> resDel = resDetailMapper.readValue(detailStr,Map.class);
            Map<String,Object> detailMap = (Map<String, Object>) resDel.get("result");
            //System.out.println("订单详情~~~~~"+detailMap);
            return detailMap;
        }catch (Exception  e){
            return null;
        }
    }
    //账单详情
    public Map<String, Object> getBillList(String accesstoken,String orderId,int pageNum) throws JsonProcessingException {
        String billUrl = aiDouConfig.getGetBillUrl()+orderId+"&pageNumber=1&pageSize=20" ;
        //get
        String billStr =  Tool.getRequest(billUrl,accesstoken,"",null,"");
        //System.out.println("账单详情~~~~~"+billStr);
        ObjectMapper resbillMapper = new ObjectMapper();
        Map<String,Object> resBill=resbillMapper.readValue(billStr,Map.class);
        //System.out.println("账单详情~~~~~"+resBill);
        Map<String, Object> billMap = (Map<String, Object>) resBill.get("result");
        return billMap;
    }
}
